/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package desu.bean;

import desu.nya.Anime;
import desu.nya.Cover;
import desu.nya.DAO.AnimeFactory;
import desu.nya.Studio;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.ManagedBean;
import javax.faces.application.FacesMessage;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UISelectItems;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author Fess
 */
@ManagedBean
@SessionScoped
public class Creating {
    private String newName="";
    private List<String> newGenre;
    private String newTypeId;
    private String newChapt="0";
    private String newCountOfSer="0";
    private String newDuration="0";
    private String newDirector="";
    private String newStudioId;
    private String createdStudioName;
    private String newCoverId;
    private String newHref="";
    private StreamedContent fileImg;
    private StreamedContent notFoundImage;
    private Anime anime=null;
    private Date dateOp;
    private Date dateEnd;
    
    private List<String> genres;
    private UISelectItems som;

    public UISelectItems getSom() {
        return som;
    }

    public void setSom(UISelectItems som) {
        this.som = som;
    }
    
    public String getCreatedStudioName() {
        return createdStudioName;
    }

    public void setCreatedStudioName(String createdStudioName) {
        this.createdStudioName = createdStudioName;
    }
    
    public Date getDateEnd() {
        return dateEnd;
    }

    public Date getDateOp() {
        return dateOp;
    }

    public void setDateOp(Date dateOp) {
        this.dateOp = dateOp;
    }

    public void setDateEnd(Date dateEnd) {
        this.dateEnd = dateEnd;
    }

    public String getNewCountOfSer() {
        return newCountOfSer;
    }

    public String getNewCoverId() {
        return newCoverId;
    }

    public String getNewDirector() {
        return newDirector;
    }

    public String getNewChapt() {
        return newChapt;
    }

    public String getNewDuration() {
        return newDuration;
    }

    public List<String> getNewGenre() {
        return newGenre;
    }

    
    public String getNewHref() {
        return newHref;
    }

    public String getNewName() {
        return newName;
    }

    public String getNewStudioId() {
        return newStudioId;
    }

    public String getNewTypeId() {
        return newTypeId;
    }

    public void setNewChapt(String newChapt) {
        this.newChapt = newChapt;
    }

    public void setNewCountOfSer(String newCountOfSer) {
        this.newCountOfSer = newCountOfSer;
    }

    public void setNewCoverId(String newCoverId) {
        this.newCoverId = newCoverId;
    }

    public void setNewDirector(String newDirector) {
        this.newDirector = newDirector;
    }

    public void setNewDuration(String newDuration) {
        this.newDuration = newDuration;
    }

    public void setNewGenre(List<String> newGenre) {
        this.newGenre = newGenre;
    }

    public void setNewHref(String newHref) {
        this.newHref = newHref;
    }

    public void setNewName(String newName) {
        this.newName = newName;
    }

    public void setNewStudioId(String newStudioId) {
        this.newStudioId = newStudioId;
    }

    public void setNewTypeId(String newTypeId) {
        this.newTypeId = newTypeId;
    }

    public Anime getAnime() {
        return anime;
    }
    
    public Creating(){
        
    }
    
    public StreamedContent getFileImg() {
        if(fileImg!=null)
            return fileImg;
        String filePath="c:\\not_found.jpg";
        FileInputStream file;
        byte[] b;
        try {
            file = new FileInputStream(filePath);
            if(file==null){
                System.err.println("File Read Error");
            }
            int count=file.available();
            b=new byte[count];
            file.read(b);
            notFoundImage=new DefaultStreamedContent(new ByteArrayInputStream(b), "image/jpg");
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
        return notFoundImage;
    }
    
    
    public void animeAdd(){
        
        AnimeFactory factory=AnimeFactory.getInstance();
        Long te=Long.parseLong(newTypeId);
        int cos=Integer.parseInt(newCountOfSer);
        int dur=Integer.parseInt(newDuration);
        Long stud=Long.parseLong(newStudioId);
        Long cov=Long.parseLong(newCoverId);
        anime=factory.getAnimeDAO().createAnimeWithStr(newName, te, newChapt, cos, dur, newDirector, stud, null, newHref);
        
        String filePath="d:\\Fess\\work\\AnimeDB\\img\\"+cov+".jpg";
        String fileSmallPath="d:\\Fess\\work\\AnimeDB\\img\\small\\"+cov+".jpg";
        FileInputStream file;
        byte[] b;
        FacesContext context=FacesContext.getCurrentInstance();
        try {
            if(factory.getAnimeDAO().isExistByHref(Long.parseLong(newHref))){
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"That anime exist in DB","Error"));
                return;
            }
            file = new FileInputStream(filePath);
            if(file==null){
                System.err.println("File Read Error");
                return;
            }
            int count=file.available();
            b=new byte[count];
            file.read(b);
            fileImg=new DefaultStreamedContent(new ByteArrayInputStream(b), "image/jpg");
            Cover cover=new Cover(b);
            file = new FileInputStream(fileSmallPath);
            count=file.available();
            b=new byte[count];
            file.read(b);
            cover.setSmallImage(b);
            anime.setDateOp(dateOp);
            anime.setDateEnd(dateEnd);
            anime.setCover(cover);
            
            
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Anime was add","Success"));
        }
        catch(Exception ex){
            ex.printStackTrace();
            context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,ex.getMessage(),"Error"));
        }
    }
    
    
    
    public void worldArtParse(){
        FacesContext cont=FacesContext.getCurrentInstance();
        AnimeFactory factory=AnimeFactory.getInstance();
        anime=null;
        try {
            if(factory.getAnimeDAO().isExistByHref(Long.parseLong(newHref))){
                cont.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"That anime exist in DB","Error"));
                return;
            }
            Document doc=Jsoup.connect("http://www.world-art.ru/animation/animation.php?id="+newHref).get();
            Elements aniInfo=doc.select("html body table tbody tr td center table tbody tr td table tbody tr td table tbody tr td[valign]");
            Element str=aniInfo.first().nextElementSibling().nextElementSibling();
            Element tempEl;
            //Name + Chapter
            String sss=str.getElementsByTag("b").first().text();
            String hrefYear="http://www.world-art.ru/animation/list.php?public_year=";
            String hrefGenre="http://www.world-art.ru/animation/list.php";
            String hrefPeople="http://www.world-art.ru/people.php?id=";
            int indOf=sss.indexOf("[");
            if(indOf!=-1){
                newName=sss.substring(0, indOf);
                if((sss.indexOf("]")-indOf)<4)
                    newChapt="1";
                else
                    newChapt=sss.substring(indOf+4,sss.indexOf("]"));
            }
            else
                newName=sss;
            //Genre
            Elements els=str.getElementsByAttributeValue("href", hrefGenre);
            genres=new ArrayList<String>();
            for(Element el:els){
                genres.add(el.text());
            }
            
            newGenre=factory.getGenreDAO().getIdListByNameList(genres);
            
            //Type Edition, Size, Duration
            String info="";
            tempEl=(Element)str.childNode(str.childNodes().size()-1);
            for(TextNode tn:tempEl.textNodes()){
                if(tn.text().length()>8){
                    info=tn.text();
                    break;
                }
            }
            //Size
            if(info.indexOf("(")!=-1&&info.indexOf("эп.")!=-1)
                newCountOfSer=info.substring(info.indexOf("(")+1,info.indexOf("эп.")-1);
            else
                newCountOfSer="0";
            //Type Edition
            if(info.contains("ТВ"))newTypeId="1";
            if(info.contains("полнометражный фильм"))newTypeId="4";
            if(info.contains("короткометражный фильм"))newTypeId="6";
            if(info.contains("OVA"))newTypeId="2";
            if(info.contains("ONA"))newTypeId="3";
            if(info.contains("ТВ-спэшл"))newTypeId="5";
            if(info.contains("музыкальное видео"))newTypeId="5";
            //Duration
            indOf=info.indexOf("мин");
            if(indOf!=-1)
                newDuration=info.substring(info.indexOf(",")+2, indOf-1);
            else 
                newDuration="-1";
            //Date
            els=str.getElementsByAttributeValueStarting("href", hrefYear);
            Iterator<Element> it=els.iterator();
            Calendar cal=Calendar.getInstance();
            int year,month,day;
            //DateOp
            if(it.hasNext()&&it.next()!=null){
                day=Integer.parseInt(it.next().text());
                month=Integer.parseInt(it.next().text());
                year=Integer.parseInt(it.next().text());
                cal.set(year, month, day);
                dateOp=cal.getTime();
            }
            else dateOp=null;
            //DateEnd
            if(it.hasNext()){
                day=Integer.parseInt(it.next().text());
                month=Integer.parseInt(it.next().text());
                year=Integer.parseInt(it.next().text());
                cal.set(year, month, day);
                dateEnd=cal.getTime();
            }
            else dateEnd=null;
            //Director
            els=str.getElementsByAttributeValueStarting("href", hrefPeople);
            if(els.size()>0)
                newDirector=els.first().text();
            else
                newDirector="";
            //Studio
            Elements studioInfo=doc.select("html body table tbody tr td center table tbody tr td table tbody tr td table tbody tr td a img[align]");
            int idWA;
            if(studioInfo.isEmpty())idWA=0;
            else{
                String studioPath=studioInfo.first().attributes().get("src");
                idWA=Integer.parseInt(studioPath.substring(studioPath.indexOf("company")+8, studioPath.indexOf(".jpg")));
            }
            Studio tStudio=factory.getStudioDAO().getStudioByIdFromWA(idWA);
//            Long tId=.getId();
            if(tStudio!=null)
                newStudioId=tStudio.getId().toString();
            else{
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "STUDIO NOT FOUND", "Studio not found"));
                tStudio=getStudioParseFromWA(idWA);
                factory.getStudioDAO().addStudio(tStudio);
                List<SelectItem> somValue=(List<SelectItem>)som.getValue();
                somValue.add(new SelectItem(tStudio.getId(), tStudio.getStudioName(), tStudio.getStudioName(), false));
                som.setValue(somValue);
                newStudioId=tStudio.getId().toString();
                System.err.print(somValue);
            }
            newCoverId=newHref;
            //Image
            String filePath="d:\\Fess\\work\\AnimeDB\\img\\"+newHref+".jpg";
            FileInputStream file;
            byte[] b;
            file = new FileInputStream(filePath);
            if(file==null){
                System.err.println("File Read Error");
                return;
            }
            int count=file.available();
            b=new byte[count];
            file.read(b);
            fileImg=new DefaultStreamedContent(new ByteArrayInputStream(b), "image/jpg");
            
            cont.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Anime: "+newName+" successfully parsed" ,"Success"));
        } catch (IOException ex) {
            ex.printStackTrace();
            cont.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,ex.getMessage(),"Error"));
        } catch (SQLException ex){
            ex.printStackTrace();
            cont.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,ex.getMessage(),"Error"));
        }
    }
    
    public void hrefNextSearch(){
            Integer href=Integer.parseInt(newHref);
            href++;
            Integer highLimit=10000;
            String filePath="d:\\Fess\\work\\AnimeDB\\img\\";
            String tPath;
            FileInputStream file=null;
            int i;
            for(i=href;file==null&&i<highLimit;i++)
                try {
                    tPath=filePath+i+".jpg";
                    file = new FileInputStream(tPath);
                }
                catch (FileNotFoundException ex) {
                }
            newHref=String.valueOf(i-1);
            worldArtParse();
            FacesContext cont=FacesContext.getCurrentInstance();
        
    }
    
    public void animeSave(){
        FacesContext cont=FacesContext.getCurrentInstance();
        AnimeFactory factory=AnimeFactory.getInstance();
        List<Long> genreListId=new ArrayList<Long>();
        for(String str:newGenre)
            genreListId.add(Long.parseLong(str));
        try {
            factory.getAnimeDAO().addAnime(anime);
            factory.getGenreListDAO().appendGenreListToAnime(anime, genreListId);
            cont.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Anime saved successfully","Error"));
        } catch (SQLException ex) {
            cont.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,ex.getMessage(),"Error"));
        }
        anime=null;
    }
    
    public List<String> getGenreList(){
        return genres;
    }
    
    private Studio getStudioParseFromWA(int idWA){
        Studio retStudio=null;
        FacesContext cont=FacesContext.getCurrentInstance();
        try {
            Document doc=Jsoup.connect("http://www.world-art.ru/company.php?id="+idWA).get();
            Elements studioInfo=doc.select("html body table tbody tr td center table tbody tr td table tbody tr td table tbody tr td font[size]");
            Element studioTag=studioInfo.first();
            String studioName=studioTag.text();
            if(studioName!=null){
                retStudio=new Studio(studioName);
                retStudio.setIdWa(idWA);
            }
            cont.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Studio: "+studioName+" was added successfully","Cool"));
        } catch (IOException ex) {
            cont.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"New Studio was failed to added","It's sad"));
        }
        return retStudio;
    }
    
    public void test(){
        try {
            AnimeFactory fact=AnimeFactory.getInstance();
            fact.getAnimeDAO().altNameCheck();
        } catch (SQLException ex) {
            FacesContext cont=FacesContext.getCurrentInstance();
            cont.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Alt_Name check error","It's sad"));
        }
    }
}
